const res = uni.getSystemInfoSync();

var token = "";
var denglu = true;
// 引入SDK核心类


var deviceInfo = {
	model: res.model,
	version: res.version,
	system: res.system,
	platform: res.platform
};
const AjaxRequest = {
	/**
	 * url 请求路径
	 * params 请求参数
	 * showloading 是否显示加载提示
	 */
	get(url, params, showLoading) {
		return new Promise((resolve) => {
			AjaxRequest.request(url, params, showLoading, "GET", (res) => {
				resolve(res)
				if (res.data.code == 4000 || res.data.code == 4001 || res.data.code == 1001) {
					uni.reLaunch({
						url: '/pages/login/login/index'
					})
					return false
				}
			})
		})
	},
	/**
	 * url 请求路径
	 * params 请求参数
	 * showloading 是否显示加载提示
	 */
	post(url, params, showLoading) {
		return new Promise((resolve) => {
			AjaxRequest.request(url, params, showLoading, "POST", (res) => {
				resolve(res)
				// console.log(res)
				if (denglu == true) {
					if (res.data.code == 4000 || res.data.code == 4001 || res.data.code == 1001) {
						denglu = false;
							uni.reLaunch({
								url:'/pages/login/login/index',
								fail:function(){
									console.log('s')
									uni.reLaunch({
										url:'/pages/login/login/index'
									})
								}
							})
						setTimeout(() => {
							denglu = true;
						}, 1000)

					}
				}

			})
		})
	},
	/**
	 * url 请求路径
	 * params 请求参数
	 * showloading 是否显示加载提示
	 */
	delete(url, params, showLoading) {
		return new Promise((resolve) => {
			AjaxRequest.request(url, params, showLoading, "DELETE", (res) => {
				resolve(res)
				if (res.data.code == 4000 || res.data.code == 4001 || res.data.code == 1001) {
					uni.navigateTo({
						url:'/pages/login/login/index'
					})
					return false
				}
			})
		})
	},
	
	put(url, params, showLoading) {
		return new Promise((resolve) => {
			AjaxRequest.request(url, params, showLoading, "PUT", (res) => {
				resolve(res)
				if (res.data.code == 4000 || res.data.code == 4001 || res.data.code == 1001) {
					uni.navigateTo({
						url:'/pages/login/login/index'
					})
					return false
				}
			})
		})
	},
	/**
	 * 文件上传
	 * @param {Object} url 请求路径
	 * @param {Object} filePath 文件路径
	 * @param {Object} showLoading 是否显示加载提示
	 */
	fileUpload(url, filePath, showLoading) {

		// const userInfo = store.state.userInfo;
		// if (userInfo) {
		// 	token = userInfo.token;
		// 	deviceInfo.userId=userInfo.id;
		// }
		return new Promise((resolve) => {
			if (showLoading) {
				uni.showLoading({
					title: "上传中..."
				})
			}
			uni.uploadFile({
				url: url,
				filePath: filePath,
				name: 'file',
				header: {
					"Authorization": token,
					"deviceInfo": JSON.stringify(deviceInfo)
				},
				success: (res) => {
					resolve(res)
				},
				fail(e) {
					console.log(JSON.stringify(e));
					util.tips("上传失败");
				},
				complete(e) {
					if (showLoading) {
						uni.hideLoading()
					}
				}
			})
		})
	},
	/**
	 * 文件批量上传
	 * @param {Object} url 请求路径
	 * @param {Object} files 文件列表
	 * @param {Object} showLoading 是否显示加载提示
	 */
	fileBatchUpload(url, files, showLoading) {

		// const userInfo = store.state.userInfo;
		// if (userInfo) {
		// 	token = userInfo.token;
		// 	deviceInfo.userId=userInfo.id;
		// }
		return new Promise((resolve) => {
			if (showLoading) {
				uni.showLoading({
					title: "上传中..."
				})
			}
			uni.uploadFile({
				url: url,
				files: files,
				header: {
					'Authorization': uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
				success: (res) => {
					resolve(res)
				},
				fail(e) {
					console.log(JSON.stringify(e));
					util.tips("上传失败");
				},
				complete(e) {
					if (showLoading) {
						uni.hideLoading()
					}
				}
			})
		})
	},
	/**
	 * 工具内方法 
	 * @param {Object} url 请求地址
	 * @param {Object} params 参数
	 * @param {Object} showLoading 是否显示加载提示
	 * @param {Object} callBack 回调函数
	 * @param {Object} method 请求方法
	 */
	request(url, params, showLoading, method, callBack) {
		var token = "";


		// const userInfo = store.state.userInfo;
		// if (userInfo) {
		// 	token = userInfo.token;
		// 	deviceInfo.userId=userInfo.id;
		// }
		if (showLoading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			})
		}
		uni.request({
			url: url,
			method: method,
			header: {
				'Content-Type': 'application/json',
				'Authorization': uni.getStorageSync('token')
				// 'appkey': 'a78ea18c7e9cd596dd7b0efd3ac17f5d'
			},
			data: params,
			success: (res) => {
				callBack(res)
			},
			fail(e) {
				util.tips("请求失败：" + JSON.stringify(e));
			},
			complete(e) {
				if (showLoading) {
					uni.hideLoading()
				}
			}
		});
	},
	/**
	 * 支付
	 * @param {Object} channel 支付通道
	 * @param {Object} paymentData 订单数据
	 * @param {Object} callBackFun 支付回调函数
	 */
	pay(channel, paymentData, callBackFun) {
		// #ifdef APP-PLUS
		let orderInfo = "";
		if (channel == "alipay") {
			orderInfo = paymentData;
		} else {
			orderInfo = JSON.stringify(paymentData);
		}
		uni.requestPayment({
			provider: channel,
			orderInfo: orderInfo,
			success: (e) => {
				uni.showToast({
					title: "支付成功!",
					icon: "none"
				})
				callBackFun(true);
			},
			fail: (e) => {
				uni.showModal({
					content: "支付失败,原因为: " + JSON.stringify(e),
					showCancel: false
				})
				callBackFun(false);
			}
		})
		// #endif

		// #ifdef MP-WEIXIN
		uni.requestPayment({
			timeStamp: paymentData.timeStamp,
			nonceStr: paymentData.nonceStr,
			package: paymentData.package,
			signType: 'MD5',
			paySign: paymentData.paySign,
			success: (res) => {
				callBackFun(true);
				uni.showToast({
					title: "支付成功!",
					icon: "none"
				})
			},
			fail: (res) => {
				callBackFun(false);
				uni.showModal({
					content: "支付失败,原因为: " + res.errMsg,
					showCancel: false
				})
			},
			complete: () => {
				this.loading = false;
			}
		})
		// #endif
	}
}
const util = {
	//返回
	back(delta) {
		delta = !delta ? 1 : delta;
		uni.navigateBack({
			delta: delta,
		})
	},
	/**
	 * 获取分享通道
	 */
	getShareChannel(callBackFun) {
		uni.getProvider({
			service: 'share',
			success: (e) => {
				let data = []
				for (let i = 0; i < e.provider.length; i++) {
					switch (e.provider[i]) {
						case 'weixin':
							data.push({
								name: '微信好友',
								id: 'weixin',
								type: 'WXSceneSession',
								img: '/static/tempimg/wechat.png',
								sort: 0
							})
							data.push({
								name: '微信朋友圈',
								id: 'weixin',
								type: 'WXSenceTimeline',
								img: '/static/tempimg/pengyouquan.png',
								sort: 1
							})
							break;
							// 						case 'sinaweibo':
							// 							data.push({
							// 								name: '分享到新浪微博',
							// 								id: 'sinaweibo',
							// 								sort:2
							// 							})
							// 							break;
						case 'qq':
							data.push({
								name: '手机QQ',
								id: 'qq',
								img: '/static/tempimg/qq.png',
								sort: 2
							})
							break;
						default:
							break;
					}
				}
				let providerList = data.sort((x, y) => {
					return x.sort - y.sort
				});
				callBackFun(providerList);
			},
			fail: (e) => {
				console.log('获取分享通道失败', e);
				uni.showModal({
					content: '获取分享通道失败',
					showCancel: false
				})
			}
		});
	},
	/**
	 * provider 选择的分享通道
	 * p:{
		 title: 标题
		 shareText: 分享的文字内容
		 shareType: 分享的类型 0图文 1纯文字 2纯图片 3音乐 4视频 5小程序
		 image: 图片地址
		 url 分享跳转的链接
	 *  }
	 */
	async share(provider, p) {
		console.log('分享通道:' + provider.id + '； 分享类型:' + p.shareType);

		if (!p.shareText && (p.shareType === 1 || p.shareType === 0)) {
			uni.showModal({
				content: '分享内容不能为空',
				showCancel: false
			})
			return;
		}

		if (!p.image && (p.shareType === 2 || p.shareType === 0)) {
			uni.showModal({
				content: '分享图片不能为空',
				showCancel: false
			})
			return;
		}

		let shareOPtions = {
			provider: provider.id,
			scene: provider.type && provider.type === 'WXSenceTimeline' ? 'WXSenceTimeline' : 'WXSceneSession', //WXSceneSession”分享到聊天界面，“WXSenceTimeline”分享到朋友圈，“WXSceneFavorite”分享到微信收藏     
			type: p.shareType,
			success: (e) => {
				console.log('success', e);
				uni.showModal({
					content: '分享成功',
					showCancel: false
				})
			},
			fail: (e) => {
				console.log('fail', e)
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				})
			},
			complete: function() {
				console.log('分享操作结束!')
			}
		}

		switch (p.shareType) {
			case 0:
				shareOPtions.summary = p.shareText;
				shareOPtions.imageUrl = p.image;
				shareOPtions.title = p.title;
				shareOPtions.href = p.url;
				break;
			case 1:
				shareOPtions.summary = p.shareText;
				break;
			case 2:
				shareOPtions.imageUrl = p.image;
				break;
			case 5:
				shareOPtions.imageUrl = p.image ? p.image : 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/app/share-logo@3.png'
				shareOPtions.title = p.title;
				shareOPtions.miniProgram = {
					id: 'gh_33446d7f7a26',
					path: '/pages/tabBar/component/component',
					webUrl: 'https://uniapp.dcloud.io',
					type: 0
				};
				break;
			default:
				break;
		}

		if (shareOPtions.type === 0 && plus.os.name === 'iOS') { //如果是图文分享，且是ios平台，则压缩图片 
			if (p.image.indexOf("https") > -1 || p.image.indexOf("http") > -1) {
				shareOPtions.imageUrl = p.image;
			} else {
				util.compress(p.image, (path) => {
					shareOPtions.imageUrl = path;
				});
			}

		}
		if (shareOPtions.type === 1 && shareOPtions.provider === 'qq') { //如果是分享文字到qq，则必须加上href和title
			shareOPtions.href = p.url;
			shareOPtions.title = p.title;
		}
		uni.share(shareOPtions);
	},
	compress(imgPath, callBackFun) { //压缩图片 图文分享要求分享图片大小不能超过20Kb
		var localPath = imgPath;
		if (imgPath.indexOf("file://") > -1) {
			localPath = plus.io.convertAbsoluteFileSystem(imgPath.replace('file://', ''));
		}
		var name = "_doc/upload/F_ZDDZZ_" + (new Date()).valueOf() + ".jpg"; //拼装唯一图片值  
		// 压缩size
		plus.io.resolveLocalFileSystemURL(localPath, (entry) => {
			entry.file((file) => { // 可通过entry对象操作图片 
				plus.zip.compressImage({
					src: imgPath,
					dst: name,
					width: '80px',
					height: '80px',
					quality: 0.8,
					overwrite: true
				}, (event) => {
					let newImg = name;
					callBackFun(newImg);
				}, function(error) {
					uni.showModal({
						content: '分享图片太大,需要请重新选择图片!',
						showCancel: false
					})
				});
			});
		}, (e) => {
			console.log('Resolve file URL failed: ' + e.message);
			uni.showModal({
				content: '分享图片太大,需要请重新选择图片!',
				showCancel: false
			})
		});
	},
	/**
	 * 从相册或摄像头拍照图片
	 * @param {Object} count 选取数量
	 * @param {Object} callBackFun 回调函数
	 */
	chooseImg: function(count, callBackFun) {
		uni.chooseImage({
			count: count, //默认9
			sizeType: ['compressed'], //original 原图，compressed 压缩图，默认二者都有
			success: function(res) {
				callBackFun(res)
			}
		});
	},
	/**
	 * 获取文件的base64
	 * @param {Object} path 文件路径
	 */
	getBase64: function(path) {
		var img = new Image();
		img.src = path; // 传过来的图片路径在这里用。
		img.onload = function() {
			var that = this;
			//生成比例 
			var w = that.width,
				h = that.height;
			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			$(canvas).attr({
				width: w,
				height: h
			});
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1最清晰，越低越模糊。
			return base64;
		};
	},
	//获取登录通道
	getLoginChannel(callBackFun) {
		uni.getProvider({
			service: 'oauth',
			success: (result) => {
				let providerList = [];
				result.provider.map((value) => {
					let providerName = '';
					let img = '';
					switch (value) {
						case 'weixin':
							providerName = '微信登录';
							img = "../../../static/tempimg/wechat.png";
							break;
						case 'qq':
							providerName = 'QQ登录';
							img = "../../../static/tempimg/qq.png";
							break;
							// 						case 'sinaweibo':
							// 							providerName = '新浪微博登录'
							// 							break;
							// 						case 'xiaomi':
							// 							providerName = '小米登录'
							// 							break;
							// 						case 'alipay':
							// 							providerName = '支付宝登录'
							// 							break;
							// 						case 'baidu':
							// 							providerName = '百度登录'
							// 							break;
							// 						case 'toutiao':
							// 							providerName = '头条登录'
							// 							break;
					}
					if (value == 'weixin' || value == "qq") {
						let obj = {
							name: providerName,
							id: value,
							img: img
						};
						providerList.push(obj)
					}
				});
				callBackFun(providerList);
			},
			fail: (error) => {
				console.log('获取登录通道失败', error);
			}
		});
	},
	//第三方登录共用方法
	thirdLogin(id, callBackFun) {
		uni.login({
			provider: id,
			success: function(loginRes) {
				// 获取用户信息
				uni.getUserInfo({
					provider: id,
					success: function(infoRes) {
						callBackFun(infoRes)
					}
				});
			}
		});
	},

	//获取缓存
	getData: function(key) {
		var data = uni.getStorageSync(key);
		return data;
	},
	//存储缓存
	setData: function(key, value) {
		uni.setStorage({
			key: key,
			data: value,
		})
	},
	//tips提示
	tips: function(msg) {
		uni.showToast({
			title: msg,
			duration: 2000,
			position: "center",
			icon: "none"
		})
	},
	/**
	 * 打开新的窗口
	 * @param string url 页面路径
	 * @param boolean doesCheckLogin 是否需要检查登录
	 */
	openWindow: function(url, doesCheckLogin) {
		if (doesCheckLogin) {
			const userInfo = uni.getStorageSync("smUser");
			if (!userInfo || userInfo == null) {
				util.tips("没有登录，快去登录吧");
				return false;
			}
		}
		uni.navigateTo({
			url: url
		});
	},
	/**
	 * 时间格式化
	 * @param string fmt 日期格式
	 * @param string date 日期
	 */
	dateFormat: function(fmt, date) {
		var o = {
			"M+": date.getMonth() + 1, //月份
			"d+": date.getDate(), //日
			"h+": date.getHours(), //小时
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			"S": date.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" +
				o[k]).substr(("" + o[k]).length)));
		return fmt;
	},
	getTimeDay(time) {
		let oldDate = new Date(time);
		let oldTime = oldDate.getTime();
		let date = new Date();
		let currentTime = date.getTime();
		let min = currentTime - oldTime; //时间差

		let s = 1000; //秒值
		let mm = 60000; //分钟毫秒值
		let h = 3600000; //1小时毫秒值

		let d = 86400000; //1天毫秒值
		let m = 0; //月毫秒值
		let ms = [1, 3, 5, 7, 8, 10, 12]; //判断月份
		let cm = date.getMonth() + 1;
		if (ms.indexOf(cm) > -1) {
			m = 2678400000;
		} else {
			m = 2592000000;
		};

		let oldY = oldDate.getFullYear();
		let curY = date.getFullYear();

		if (curY > oldY) {
			return (curY - oldY) + "年前";
		} else if (min < s) {
			return "刚刚";
		} else if (min > s && min < mm) {
			return parseInt(min / s) + "秒前";
		} else if (min > mm && min < h) {
			return parseInt(min / mm) + "分钟前";
		} else if (min > h && min < d) {
			return parseInt(min / h) + "小时前";
		} else if (min > d && min < m) {
			return parseInt(min / d) + "天前"
		} else if (min > m) {
			return parseInt(min / m) + "月前"
		}
	},
	/**
	 * 获取系统信息
	 * @param {Object} callBack
	 */
	getSystenInfo(callBack) {
		uni.getSystemInfo({
			success: function(res) {
				callBack(res)
			}
		});
	},
	/**
	 * 获取当前设备网络环境
	 */
	getNetWorkState() {
		var NetStateStr = '未知';
		var types = {};
		types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
		types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
		types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
		types[plus.networkinfo.CONNECTION_WIFI] = "WiFi网络";
		types[plus.networkinfo.CONNECTION_CELL2G] = "2G蜂窝网络";
		types[plus.networkinfo.CONNECTION_CELL3G] = "3G蜂窝网络";
		types[plus.networkinfo.CONNECTION_CELL4G] = "4G蜂窝网络";
		NetStateStr = types[plus.networkinfo.getCurrentType()];
		return NetStateStr === "未知" || NetStateStr === "未连接网络" ? false : true;
	},
	/**
	 * 位置选择
	 * @param {Object} callBackFun
	 */
	chooseLocation(callBackFun) {
		uni.chooseLocation({
			success(e) {
				//把获取到到位置进行拆解，处理成可用的字段
				let name = e.address;
				let province = name.substring(0, name.indexOf("省") + 1);
				let city = name.substring(name.indexOf("省") + 1, name.indexOf("市") + 1);
				let poiName = name.substring(name.indexOf("市") + 1, name.length);
				let address = {
					"country": "中国",
					"province": province,
					"city": city,
					"street": null,
					"poiName": poiName
				};
				let coords = {
					"latitude": e.latitude,
					"longitude": e.longitude
				};
				let location = {
					address: address,
					coords: coords
				}
				callBackFun(location);
			}
		})
	},
	/**
	 * 检查手机格式是否争取
	 * @param {Object} phone
	 */
	isPhone(phone) {
		if (!/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(phone)) {
			return false;
		} else {
			return true;
		}
	},
	/**
	 * 获取支付通道
	 * @param {Object} callBackFun
	 */
	getPayProvider(callBackFun) {
		uni.getProvider({
			service: "payment",
			success: (e) => {
				let providerList = [];
				e.provider.map((value) => {
					switch (value) {
						case 'alipay':
							providerList.push({
								name: '支付宝',
								id: value,
								img: "../../static/order_submit_12.png",
								value: "1300001"
							});
							break;
						case 'wxpay':
							providerList.push({
								name: '微信',
								id: value,
								img: "../../static/order_submit_09.png",
								value: "1300002"
							});
							break;
						default:
							break;
					}
				})
				callBackFun(providerList);
			},
			fail: (e) => {
				console.log("获取支付通道失败：", e);
			}
		});
	},

	/**
	 * 根据地理位置转化成坐标点
	 * @param {Object} address
	 * @param {Object} city
	 * @param {Object} callBackFun
	 */
	geocodeLocation(address, city, callBackFun) {
		// #ifdef APP-PLUS
		let options = {};
		if (city != null && city != "") {
			options.city = city;
		}
		plus.maps.Map.geocode(address, options, function(event) {
			callBackFun(event);
		}, function(e) {
			alert("Failed:" + JSON.stringify(e));
		});
		// #endif
	},
	/**
	 * @description 坐标转换为地理未知
	 * @param {Object} latitude
	 * @param {Object} longitude
	 * @param {Object} callBackFun
	 */
	reverseGeocoder(latitude, longitude, callBackFun) {

		//根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: latitude,
				longitude: longitude
			},
			success: function(res) {
				callBackFun(res)
			}
		})
	},
	getFileBase64(filePath, callBackFun) {
		plus.io.resolveLocalFileSystemURL(filePath, file => {
			file.file(vf => {
				console.log(vf.name);
				let fileReader = new plus.io.FileReader();
				fileReader.readAsDataURL(vf);
				fileReader.onloadend = result => {
					callBackFun(result.target.result);
				}
			})
		}, error => {
			uni.showToast({
				title: '文件信息错误' + error.message
			})
		})
	},
	generateUUID() {
		var d = new Date().getTime();
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});

		return uuid.replace(/-/g, "");
	},
}
module.exports = {
	ajaxRequest: AjaxRequest,
	util: util
};
